package com.itheima.reggie.filters;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限拦截过滤器
 * @author ghy
 * @version v1.0
 * create on 2022/11/17 8:59
 */
@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {

    //路径匹配工具类，支持通配符匹配
    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.获取请求uri
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        log.error("当前线程ID:{}", Thread.currentThread().getId());

        String uri = request.getRequestURI();
        log.error("uri-->{}", uri);

        //2.判断当前请求uri是否需要拦截
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "swagger-ui.html"
        };
        if (matchUrl(uri, urls)) {
            chain.doFilter(request, response);
            return;
        }
        //2.3 拦截
        Object employee = request.getSession().getAttribute("employee");
        //3.判断当前员工是否登录
        if(employee != null) {
            //把登录的employeeId放到ThreadLocal中
            ThreadLocalUtils.set((Long) employee);
            //2.3.1 登录过，放行
            chain.doFilter(request, response);
            //把登录的employeeId从ThreadLocal上移除
            ThreadLocalUtils.remove();
            return;
        }

        Object user = request.getSession().getAttribute("user");
        //3.判断当前员工是否登录
        if(user != null) {
            //把登录的employeeId放到ThreadLocal中
            ThreadLocalUtils.set((Long) user);
            //2.3.1 登录过，放行
            chain.doFilter(request, response);
            //把登录的employeeId从ThreadLocal上移除
            ThreadLocalUtils.remove();
            return;
        }

        //2.3.2 没登录
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 匹配资源
     * @param uri
     * @param urls
     * @return
     * @throws IOException
     * @throws ServletException
     */
    private boolean matchUrl(String uri, String[] urls) {
        for (String url : urls) {
            boolean result = ANT_PATH_MATCHER.match(url, uri);
            if(result) {
                //2.2 放行
                return true;
            }
        }
        return false;
    }
}
